package org.gpf.operation;

import java.util.Iterator;
import java.util.List;

import org.gpf.factory.DAOFactory;
import org.gpf.util.InputDate;
import org.gpf.vo.User;
/**
 * 该类完成用户的增删改查，但是具体的操作交给DAO处理
 * @author gaopengfei
 * @date 2015-4-23 下午8:35:53
 */
public class Operation {

	/**
	 * 添加用户
	 */
	public static void insert(){
		
		InputDate input = new InputDate();
		User user = new User();
		user.setUsername(input.getString("请输入姓名："));
		user.setPassword(input.getString("请输入密码:"));
		user.setAge(input.getInt("请输入年龄：", "年龄必须是数字！"));
		user.setSex(input.getString("请输入性别："));
		user.setBirthday(input.getDate("请输入生日（如：1989-03-22）", "日期格式必须是yyyy-MM-dd"));
		
		DAOFactory.getIUserDAOInstance().doCreate(user);
	}
	
	/**
	 * 删除用户
	 */
	public static void delete(){
		
		InputDate input = new InputDate();
		DAOFactory.getIUserDAOInstance().doDelete(input.getInt("请输入用户id", "编号必须是数字！"));
	}
	
	/**
	 * 更新用户
	 */
	public static void update(){
		
		InputDate input = new InputDate();
		int id = input.getInt("请输入用户id", "编号必须是数字！");
		User user = DAOFactory.getIUserDAOInstance().findById(id);
		if (user!=null) {
			user.setUsername(input.getString("请输入姓名，原来的姓名：(" + user.getUsername() + ")"));
			user.setPassword(input.getString("请输入密码，原来的密码：(" + user.getPassword() + ")"));
			user.setAge(input.getInt("请输入年龄，原来的年龄：(" + user.getAge() + ")","年龄必须是数字！"));
			user.setSex(input.getString("请输入性别，原来的性别：(" + user.getSex() + ")"));
			user.setBirthday(input.getDate("请输入生日，原来的生日：(" + user.getBirthday() + ")","日期格式必须是yyyy-MM-dd"));
			
			DAOFactory.getIUserDAOInstance().doUpdate(user);
		}else {
			System.out.println("不存在id为" + id + "的用户！");
		}
	}
	
	/**
	 * 按照id查找用户
	 */
	public static void findById(){
		
		InputDate input = new InputDate();
		int id = input.getInt("请输入用户id", "编号必须是数字！");
		User user = DAOFactory.getIUserDAOInstance().findById(id);
		if (user!=null) {
			System.out.println(user);
		}else {
			System.out.println("不存在id为" + id + "的用户！");
		}
	}
	
	/**
	 * 查询所有用户
	 */
	public static void findAll(){
		
		InputDate input = new InputDate();
		String keyword = input.getString("请输入查询的关键字：");
		List<User> users = DAOFactory.getIUserDAOInstance().findAll(keyword);
		Iterator<User> iterator = users.iterator();
		while (iterator.hasNext()) {
			User user = (User) iterator.next();
			System.out.println(user);
		}
	}
}
